import React, { Component } from 'react';
import axios from "axios";

import Header from './components/Header';
import Main from './components/Main';

export class App extends Component {
  constructor(props) {
    super(props)
  
    this.state = {
       list:[],
    }
  }

  componentDidMount() {
    axios.get("/api/list").then( res => {
      this.setState({
        list: res.data,
      })
      console.log(res.data);
    })
  }

  // 1）添加 
  addFn = (value) => {
    let { list } = this.state;
    list.push({
      "id":new Date().getTime(),
      "title":value,
      "state":false
    })

    // 重新赋值 
    this.setState({
      list: list
    })
  }

  //2） 删除 
  delFn = (id) => {
    let { list } = this.state;
    list = list.filter(item => {
      return item.id !== id;
    })

    this.setState({
      list:list
    })
  }

  // 3）修改完成状态 
  changeFn = (id) => {
    let { list } = this.state;
    list = list.forEach( item => {
      if( item.id === id) {
        item.state = !item.state;
      }
    })

    this.setState({
      list:list
    })
    console.log("list",list);
  }



  render() {
    const { list } = this.state;
    return (
      <div className='App'>
        <Header add={this.addFn}></Header>
        <Main 
        list = { list }
        del={this.delFn}
        change={this.changeFn}
        
        ></Main>
      </div>
    )
  }
}

export default App